//
//  MTRegisterViewController.m
//  ebook
//
//  Created by 吴超飞 on 16/2/23.
//  Copyright © 2016年 Moton. All rights reserved.
//

#import "MTRegisterViewController.h"
#import "MTLoginViewController.h"
#import "EbookNetRequest.h"
#import "MBProgressHUD.h"
#import "MTMineViewController.h"
#import "MISAlertController.h"
#import "FileManager.h"
#import "GuestLoginManager.h"

@interface MTRegisterViewController ()<UITextFieldDelegate>{
    
    BOOL isRegisterOk;
}

@end

@implementation MTRegisterViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.view.backgroundColor = MTConfigColor(@"MTRegister_Bg_Color");
    
    [self createBackBtn];
    
    float width = MTScreenW - 40;
    float height = 0;
    if (isIpad) {
        height = 320*41/263;
    } else {
        height =  width*41/263;
    }
    self.title = @"新用户注册";
    
    _usernameField = [[UITextField alloc] initWithFrame:CGRectMake(20, 38, width, height)];
    _usernameField.backgroundColor = MTConfigColor(@"MTRegister_nameFieldBg_Color");
    _usernameField.layer.cornerRadius = 3.0f;
    _usernameField.placeholder = @"请输入用户名称";
    _usernameField.tag = 1;
    _usernameField.delegate = self;
    _usernameField.font = [UIFont systemFontOfSize:16.0f];
    UIImageView* usernameIconImage = [[UIImageView alloc] initWithFrame:CGRectMake(9, 9, 19/3*2, 30/3*2)];
    usernameIconImage.image = [UIImage imageNamed:@"user"];
    
    UIView *usernameContainer = [[UIView alloc] initWithFrame:CGRectMake(0, 0, height+15, height)];
    usernameContainer.backgroundColor = MTConfigColor(@"MTRegister_nameContain_Color");
    
    UIView* usernameIconContainer = [[UIView alloc] initWithFrame:CGRectMake(0, 0, height, height)];
    usernameIconContainer.backgroundColor = [UIColor colorWithWhite:0.9 alpha:0.7];
    usernameIconImage.center = usernameIconContainer.center;
    [usernameIconContainer addSubview:usernameIconImage];
    [usernameContainer addSubview:usernameIconContainer];
    _usernameField.leftViewMode = UITextFieldViewModeAlways;
    _usernameField.leftView = usernameContainer;
    
    _passwordField = [[UITextField alloc] initWithFrame:CGRectMake(20, CGRectGetMaxY(_usernameField.frame)+12, width, height)];
    _passwordField.backgroundColor = MTConfigColor(@"MTRegister_passwordFieldBg_Color");
    _passwordField.layer.cornerRadius = 3.0f;
    _passwordField.secureTextEntry = YES;
    _passwordField.placeholder = @"请设置用户密码";
    _passwordField.tag = 2;
    _passwordField.delegate = self;
    _passwordField.font = [UIFont systemFontOfSize:16.0f];
    UIImageView* passwordIconImage = [[UIImageView alloc] initWithFrame:CGRectMake(9, 9, 19/3*2, 30/3*2)];
    passwordIconImage.image = [UIImage imageNamed:@"pass"];
    
    UIView *passwordContainer = [[UIView alloc] initWithFrame:CGRectMake(0, 0, height+15, height)];
    passwordContainer.backgroundColor = [UIColor whiteColor];
    
    UIView* passwordIconContainer = [[UIView alloc] initWithFrame:CGRectMake(0, 0, height, height)];
    passwordIconContainer.backgroundColor = [UIColor colorWithWhite:0.9 alpha:0.7];
    passwordIconImage.center = passwordIconContainer.center;
    [passwordIconContainer addSubview:passwordIconImage];
    [passwordContainer addSubview:passwordIconContainer];
    _passwordField.leftViewMode = UITextFieldViewModeAlways;
    _passwordField.leftView = passwordContainer;
    
    UIButton *hidePassBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    hidePassBtn.frame = CGRectMake(0, 0, height, height);
    [hidePassBtn setTitle:@"显示" forState:UIControlStateNormal];
    hidePassBtn.titleLabel.font = [UIFont systemFontOfSize:16.0];
    hidePassBtn.backgroundColor = [UIColor colorWithWhite:0.9 alpha:1];
    [hidePassBtn addTarget:self action:@selector(hiddenPW:) forControlEvents:UIControlEventTouchUpInside];
    _passwordField.rightView = hidePassBtn;
    _passwordField.rightViewMode = UITextFieldViewModeAlways;
    
    
    _registerButton = [[UIButton alloc] initWithFrame:CGRectMake(20, CGRectGetMaxY(_passwordField.frame)+27, width, height)];
    _registerButton.backgroundColor = MTConfigColor(@"MTRegister_registerBtnBg_Color");
    _registerButton.layer.cornerRadius = 3.0f;
    UIColor *rigisterBtnShadowColor = MTConfigColor(@"MTRegister_registerBtnShadow_Color");
    _registerButton.layer.shadowColor = rigisterBtnShadowColor.CGColor;
    _registerButton.layer.shadowRadius = 3.0f;
    _registerButton.layer.shadowOffset = CGSizeMake(2, 2);
    _registerButton.titleLabel.font = [UIFont systemFontOfSize:15.0f];
    [_registerButton setTitle:@"注册" forState:UIControlStateNormal];
    [_registerButton setTitleColor:MTConfigColor(@"MTRegister_registerBtnTitleNormal_Color") forState:UIControlStateNormal];
    [_registerButton setTitleColor:MTConfigColor(@"MTRegister_registerBtnTitleHighlighted_Color") forState:UIControlStateHighlighted];
    [_registerButton addTarget:self action:@selector(registerButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    
    
    [self.view addSubview:self.registerButton];
    [self.view addSubview:self.usernameField];
    [self.view addSubview:self.passwordField];
    
    UIButton *closeBtn = [[UIButton alloc] initWithFrame:CGRectMake(17, 22, 40, 40)];
    closeBtn.backgroundColor = [UIColor clearColor];
    closeBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    closeBtn.titleLabel.font = [UIFont systemFontOfSize:14.0f];
    [closeBtn setImage:[UIImage imageNamed:@"back_arrow"] forState:UIControlStateNormal];
    //    [closeBtn setTitleColor:darkColor forState:UIControlStateNormal];
    [closeBtn setTitleColor:[UIColor colorWithWhite:1.0 alpha:0.5] forState:UIControlStateHighlighted];
    [closeBtn addTarget:self action:@selector(closeBtnClick:) forControlEvents:UIControlEventTouchUpInside];
}

#pragma mark - navi back btn
- (void)createBackBtn
{
    UIBarButtonItem *backItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"back_arrow"] style:UIBarButtonItemStylePlain target:self action:@selector(back)];
    backItem.tintColor = MTConfigColor(@"MTNavigationBar_leftItem_Color");
    self.navigationItem.leftBarButtonItem = backItem;
}

- (void)back
{
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)closeBtnClick:(UIButton *)btn{
    
    [self.navigationController popToRootViewControllerAnimated:YES];
}

-(BOOL)textFieldShouldReturn:(UITextField *)textField{
    
    switch (textField.tag) {
            
        case 1:
            [_passwordField becomeFirstResponder];
            break;
            
        case 2:
            [textField resignFirstResponder];
            break;
            
        default:
            break;
    }
    
    return YES;
}

- (void)hiddenPW:(UIButton *)btn
{
    if ([btn.titleLabel.text isEqualToString:@"显示"]) {
        _passwordField.secureTextEntry = NO;
        [btn setTitle:@"隐藏" forState:UIControlStateNormal];
    } else {
        _passwordField.secureTextEntry = YES;
        [btn setTitle:@"显示" forState:UIControlStateNormal];
    }
}

//注册新用户
-(void)registerButtonClick:(UIButton *)btn{
    
    [self.usernameField resignFirstResponder];
    [self.passwordField resignFirstResponder];
    
    BOOL isValidInput = YES;
    NSString *errorMsg = @"输入非法";
    if(self.usernameField.text.length<4 || self.usernameField.text.length>20){
        isValidInput = NO;
        errorMsg = @"输入用户名有误，请输入4~20个字符";
    }else if(self.passwordField.text.length==0){
        isValidInput = NO;
        errorMsg = @"请输入密码";
    }else if(![self isValidateUser:self.usernameField.text]){
        isValidInput = NO;
        errorMsg = @"用户名只能使用字母或数字";
    }
    
    if (!isValidInput) {
        
        MISAlertController *alertController = [MISAlertController alertControllerWithTitle:@"提示" message:errorMsg preferredStyle:UIAlertControllerStyleAlert];
        MISAlertAction *okAction = [MISAlertAction actionWithTitle:@"好的" style:UIAlertActionStyleDefault handler:nil];
        [alertController addAction:okAction];
        [alertController showInViewController:self animated:YES];
        return;
    }
    
    MBProgressHUD *_HUD = [[MBProgressHUD alloc]initWithFrame:CGRectMake(0, 0, 50, 50)];
    _HUD.labelText = @"注册中...";
    [_HUD show:YES];
    [self.view addSubview:_HUD];
    NSString *mdpsw = [EbookNetRequest MD5:self.passwordField.text];
    
    [GuestLoginManager registerWithName:self.usernameField.text passsword:mdpsw success:^(BOOL suc) {
        
        [_HUD removeFromSuperview];
        [self closeBtnClick:nil];//关闭注册页
        if ([self.delegate respondsToSelector:@selector(registerSuccess)]) {
            [self.delegate registerSuccess];//关闭登录页
        }
        
        [GuestLoginManager changeUserComplete];
    } failed:^(int stateCode, NSString *failMsg) {
        [_HUD removeFromSuperview];
        MISAlertController *alertController = [MISAlertController alertControllerWithTitle:@"注册失败" message:failMsg preferredStyle:UIAlertControllerStyleAlert];
        MISAlertAction *okAction = [MISAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:nil];
        [alertController addAction:okAction];
        [alertController showInViewController:self animated:YES];
    }];
}

-(BOOL)isValidateUser:(NSString *)user
{
    NSString *userRegex = @"[A-Za-z0-9]+";
    NSPredicate *userPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", userRegex];
    return [userPredicate evaluateWithObject:user];
}

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    
    [_usernameField resignFirstResponder];
    [_passwordField resignFirstResponder];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
